package nckd.wnqjt.tmc.tda.plugin.form;

import com.grapecity.documents.excel.S;
import kd.bos.ai.util.JsonUtil;
import kd.bos.algo.*;
import kd.bos.algo.input.CollectionInput;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.AppInfo;
import kd.bos.entity.AppMetadataCache;
import kd.bos.entity.qing.*;
import kd.bos.entity.qing.Field;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.form.IFormView;
import kd.bos.form.IPageCache;
import kd.bos.form.ShowType;
import kd.bos.form.control.IQingAnalysis;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.mvc.SessionManager;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.report.ReportShowParameter;
import kd.bos.servicehelper.QueryServiceHelper;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 银行借款到期预警轻分析报表查询插件
 */

public class BankLoanReminderQueryPlugin extends AbstractFormPlugin implements IQingDataProvider {

    //银行贷款类型
    private final String[] loanType = {"loan","sl","bond"};

    //提款处理查询字段
    private final String field = "id,org.name as org,bizdate,billstatus,loantype,repayplan_entry,repayplan_entry.exrepaymentdate as exrepaymentdate,repayplan_entry.enotrepayamount as enotrepayamount";

    @Override
    public QingMeta getMeta(String s) {
        String entityKey = "cfm_loanbill";
        QingMeta meta = new QingMeta();
        EntryEntity entity = new EntryEntity();
        entity.setKey(entityKey);
        entity.setName(new LocaleString("银行借款到期预警"));
        entity.setPkFieldName("id");
        meta.addEntryEntity(entity);

        Field column = new Field();
        column.setEntity(entityKey);//字段所属实体key	否
        column.setKey("id");// 字段名(唯一标识)	是
        column.setFieldType(QingFieldType.Int.toNumber()); //数据类型	是
        column.setName(new LocaleString("id")); //字段别名	是
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("org");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("借款人"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("enotrepayamount");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("未还本金"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("bizdate");
        column.setFieldType(QingFieldType.Date.toNumber());
        column.setName(new LocaleString("日期"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("month");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("月份"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("idMonth");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("穿透字段"));
        meta.addColumn(column);
        return meta;
    }

    @Override
    public QingData getData(String s, int startRow, int i1) {

        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter");

        QFilter[] billFilters = null;
        //单据状态=审核
        QFilter qFilter1 = new QFilter("billstatus", QCP.equals,"C");
        //贷款类型=银行
        QFilter qFilter2 = new QFilter("loantype", QCP.in,loanType);
        //过去一个月
        Date moth1 = getMoth(new Date(), 30);
        Date moth2 = getMoth(new Date(), 60);
        Date moth3 = getMoth(new Date(), 90);
        Date moth4 = getMoth(new Date(), 120);
        Date moth5 = getMoth(new Date(), 150);
        Date moth6 = getMoth(new Date(), 180);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse;
        try {
            parse = format.parse(format.format(new Date()));
            moth1 = format.parse(format.format(moth1));
            moth2 = format.parse(format.format(moth2));
            moth3 = format.parse(format.format(moth3));
            moth4 = format.parse(format.format(moth4));
            moth5 = format.parse(format.format(moth5));
            moth6 = format.parse(format.format(moth6));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        //查一个月内未还金额
        QFilter qFilter3 = new QFilter("repayplan_entry.exrepaymentdate",QCP.large_equals,parse)
                .and(new QFilter("repayplan_entry.exrepaymentdate",QCP.less_equals,moth1));
        billFilters = new QFilter[]{qFilter1, qFilter2,qFilter3};
        DataSet dataSet1 = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_loanbill", field, billFilters, null);
        DataSet select1 = dataSet1.select(new String[]{"id","org","bizdate","billstatus","loantype","exrepaymentdate","enotrepayamount","'1个月' as month"});
        select1 = dataSetDefaultValue(select1,"1个月");

        //查第一个月至第二个月内未还金额
        qFilter3 = new QFilter("repayplan_entry.exrepaymentdate",QCP.large_equals,moth1)
                .and(new QFilter("repayplan_entry.exrepaymentdate",QCP.less_equals,moth2));
        billFilters = new QFilter[]{qFilter1, qFilter2,qFilter3};
        DataSet dataSet2 = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_loanbill", field, billFilters, null);
        DataSet select2 = dataSet2.select(new String[]{"id","org","bizdate","billstatus","loantype","exrepaymentdate","enotrepayamount","'2个月' as month"});
        select2 = dataSetDefaultValue(select2,"2个月");

        //查第二个月至第三个月内未还金额
        qFilter3 = new QFilter("repayplan_entry.exrepaymentdate",QCP.large_equals,moth2)
                .and(new QFilter("repayplan_entry.exrepaymentdate",QCP.less_equals,moth3));
        billFilters = new QFilter[]{qFilter1, qFilter2,qFilter3};
        DataSet dataSet3 = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_loanbill", field, billFilters, null);
        DataSet select3 = dataSet3.select(new String[]{"id","org","bizdate","billstatus","loantype","exrepaymentdate","enotrepayamount","'3个月' as month"});
        select3 = dataSetDefaultValue(select3,"3个月");

        //查第三个月至第四个月内未还金额
        qFilter3 = new QFilter("repayplan_entry.exrepaymentdate",QCP.large_equals,moth3)
                .and(new QFilter("repayplan_entry.exrepaymentdate",QCP.less_equals,moth4));
        billFilters = new QFilter[]{qFilter1, qFilter2,qFilter3};
        DataSet dataSet4 = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_loanbill", field, billFilters, null);
        DataSet select4 = dataSet4.select(new String[]{"id","org","bizdate","billstatus","loantype","exrepaymentdate","enotrepayamount","'4个月' as month"});
        select4 = dataSetDefaultValue(select4,"4个月");

        //查第四个月至第五个月内未还金额
        qFilter3 = new QFilter("repayplan_entry.exrepaymentdate",QCP.large_equals,moth4)
                .and(new QFilter("repayplan_entry.exrepaymentdate",QCP.less_equals,moth5));
        billFilters = new QFilter[]{qFilter1, qFilter2,qFilter3};
        DataSet dataSet5 = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_loanbill", field, billFilters, null);
        DataSet select5 = dataSet5.select(new String[]{"id","org","bizdate","billstatus","loantype","exrepaymentdate","enotrepayamount","'5个月' as month"});
        select5 = dataSetDefaultValue(select5,"5个月");

        //查第五个月至第六个月内未还金额
        qFilter3 = new QFilter("repayplan_entry.exrepaymentdate",QCP.large_equals,moth5)
                .and(new QFilter("repayplan_entry.exrepaymentdate",QCP.less_equals,moth6));
        billFilters = new QFilter[]{qFilter1,qFilter2,qFilter3};
        DataSet dataSet6 = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_loanbill", field, billFilters, null);
        DataSet select6 = dataSet6.select(new String[]{"id","org","bizdate","billstatus","loantype","exrepaymentdate","enotrepayamount","'6个月' as month"});;
        select6 = dataSetDefaultValue(select6,"6个月");


        DataSet unioned = select1.union(select2).union(select3).union(select4).union(select5).union(select6);

        QingData data = null;
        if (startRow < 200) {
            data = new QingData();
            Map<String, Integer> dataindex = new HashMap<String, Integer>();
            dataindex.put("id", 0);
            dataindex.put("org", 1);
            dataindex.put("enotrepayamount", 2);
            dataindex.put("bizdate", 3);
            dataindex.put("month", 4);
            dataindex.put("idMonth", 5);
            data.setDataindex(dataindex);

            List<Object[]> rows = new ArrayList<Object[]>();
            while (unioned.hasNext()) {
                Row row = unioned.next();
                Object[] obj = new Object[6];
                obj[0] = row.getLong("id");
                obj[1] = row.get("org");
                obj[2] = row.getBigDecimal("enotrepayamount");
                Timestamp timestamp = (Timestamp) row.get("bizdate");
                if (timestamp != null) {
                    long time = timestamp.getTime();
                    obj[3] = time;
                }else {
                    obj[3] = null;
                }
                obj[4] = row.getString("month");
                Date exrepaymentdate = row.getDate("exrepaymentdate");
                String a = "";
                if (exrepaymentdate != null) {
                    a = new SimpleDateFormat("yyyyMMdd").format(exrepaymentdate);
                    a = row.getString("id")+a;
                }
                obj[5] = a;
                rows.add(obj);
            }
            data.setRows(rows);
        }
        return data;
    }

    private DataSet dataSetDefaultValue(DataSet dataSet, String month) {
        if (dataSet.isEmpty()) {
            // 创建一个空的DataSet
            Collection<Object[]> coll = new ArrayList<>();
            Object[] objects = {null, null, null, null, null,null, BigDecimal.ZERO, month};
            coll.add(objects);
            String[] fields = new String[]{"id", "org", "bizdate", "billstatus", "loantype", "exrepaymentdate", "enotrepayamount","month"};
            DataType[] dataTypes = new DataType[]{DataType.LongType, DataType.StringType, DataType.DateType, DataType.StringType, DataType.StringType, DataType.DateType, DataType.BigDecimalType,DataType.StringType};
            RowMeta rowMeta = RowMetaFactory.createRowMeta(fields, dataTypes);
            CollectionInput inputs = new CollectionInput(rowMeta, coll);
            dataSet = Algo.create(this.getClass().getName()).createDataSet(inputs);
        }
        return dataSet;
    }

    @Override
    public void setFilterParameter(String filterParameter) {
        IPageCache pageCache = getPageCache();
        pageCache.put("qFilter", filterParameter);

    }

    @Override
    public String getFilterParameter() {
        return getPageCache().get("qFilter");
    }

    /**
     * 计算日期
     * @param date
     * @param index
     * @return
     */
    private Date getMoth(Date date,Integer index){
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(date);
        rightNow.add(Calendar.DATE, index);
        return rightNow.getTime();
    }

    /**
     * 获取动态表单联查信息
     *
     * @param pageId
     * @param ctrKey
     * @return
     */
    @Override
    public List<QingLinkageInfo> getLinkageInfo(String pageId, String ctrKey) {
        //return IQingDataProvider.super.getLinkageInfo(pageId, ctrKey);
        List<QingLinkageInfo> infos = new ArrayList<QingLinkageInfo>();
        QingLinkageInfo info = new QingLinkageInfo();
        Map<String, String> formKey = new HashMap<>();
        AppInfo appInfo = AppMetadataCache.getAppInfo("bei");
        String formId1 = this.getView().getFormShowParameter().getAppId();
        formKey.put("AppId", appInfo.getAppId()); //需要打开的表单所在应用的id
        String formId = this.getView().getFormShowParameter().getFormId();
        formKey.put("FormId", "nckd_bankloansumquery"); //需要打开的表单的id
        formKey.put("System", "IERP");
        formKey.put("CtrKey", ctrKey);
        info.setFormKey(JsonUtil.encodeToString(formKey));
        info.setFormDisplayName("银行提款处理列表");//联查到表单的显示名称
        info.setFormPrimaryKey("idMonth");//联查到表单的主键
        infos.add(info);//可以添加多个QingLinkageInfo对象
        this.getView().getPageCache().put("qingViewControlKey", ctrKey);//必要语句!
        return infos;
    }


    /**
     * <p>调用此接口，触发业务逻辑，具体业务联查实现此接口<p/>
     *
     * @param ids    轻分析得到动态表单需要联査的1d的集合
     * @param pageId
     * @param formId
     * @param appId
     */
    @Override
    public void fireLinkageInfo(List<String> ids, String pageId, String formId, String appId) {
        //IQingDataProvider.super.fireLinkageInfo(ids, pageId, formId, appId);
        /*具体的表单打开逻辑，业务自己去实现
        ids:联查到的主键的值
        pageId:触发联査的页面的pageId，可用于找到触发联査的页面: FormView view = (FormView)Sessiomanager.getCurrent().getView(pageId)
        formId:联查到的表单的id
        appId:联查到的表单所在应用的Id
        */

        /*注意: 如果需要使用芒穹的view.showForm 方式打开表单，需要添加以下代码*/
        // 组装 FormShomParaneter(披照业务场景亲实现)
        ReportShowParameter reportShowParameter = new ReportShowParameter();
        reportShowParameter.getOpenStyle().setShowType(ShowType.Modal);
        reportShowParameter.setAppId(appId);
        reportShowParameter.setFormId(formId);//报表标识
        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter"); //从仪表板进去 拿不到
        //通过此方法拿到过滤参数
        Map<String, Object> filterParam = new HashMap<>();
        // 设置报表过滤条件
        ReportQueryParam reportQueryParam = new ReportQueryParam();
        //FilterInfo filterInfo = new FilterInfo();
        //filterInfo.addFilterItem("nckd_orgview", filterParam.get("nckd_orgview"));
        //filterInfo.addFilterItem("nckd_org", filterParam.get("nckd_org"));
        //filterInfo.addFilterItem("nckd_currency", filterParam.get("nckd_currency"));
        //filterInfo.addFilterItem("bizdate", filterParam.get("nckd_querydate"));
        //filterInfo.addFilterItem("nckd_amountunit", filterParam.get("nckd_amountunit"));
        filterParam.put("id", ids);
        //reportQueryParam.setFilter(filterInfo);
        reportQueryParam.setCustomParam(filterParam);
        reportShowParameter.setQueryParam(reportQueryParam);

        /*******************************showForm必要的代码******************************************/
        IFormView view = SessionManager.getCurrent().getView(pageId);
        String ctrKey = this.getView().getPageCache().get("qingViewControlKey");
        if (ctrKey != null) {
            if (view.getControl(ctrKey) instanceof IQingAnalysis) {
                //设计器的场景，直接showForm
                view.showForm(reportShowParameter);
                return;
            }
        }
        //其他场景需要，返回FormShowParameter，由轻分析来 showForm
        this.getView().setClientReturnData(ListShowParameter.toJsonString(reportShowParameter));
        /*******************************showForm必要的代码******************************************/
    }

}
